package com.qsmx.store.app.util;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;

import com.qsmx.store.core.util.log.AtmosLogger;

import java.util.HashMap;
import java.util.Iterator;

public class CoinOutUtil {

    private Context mContext;
    private static final String TAG = "MainActivity";
    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
    private HashMap<String, UsbDevice> deviceList;
    private UsbManager mUsbManager;
    private UsbDevice mUsbDevice;
    private UsbInterface mInterface;
    private UsbDeviceConnection mDeviceConnection;
    private int mVendorID = 0x0483;
    private int mProductID = 0x5750;
    private UsbEndpoint usbEpOut;
    private UsbEndpoint usbEpIn;

    private Thread mThread;
    private Thread mThread2;
    private Handler mHandler;

    private int byteNum;
    private int state;
    private int coinNum;
    private int keyState;
    private int ver;

    StringBuffer recvBytes = new StringBuffer();

    //USB初始化函数
    public void InitUsb(Context mContext) {
        this.mContext = mContext;
        mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        deviceList = mUsbManager.getDeviceList();

        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

        while (deviceIterator.hasNext()) {
            UsbDevice usb = deviceIterator.next();
            AtmosLogger.e(TAG, "vid=" + usb.getVendorId() + "---pid=" + usb.getProductId());
            if (IsTargetDevice(usb)) {
                OpenUsbDevice(usb);
                break;
            }
        }

        mThread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {

                    if (mHandler != null) {
                        mHandler.sendEmptyMessage(3);
                        try {
                            Thread.sleep(20);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        mThread2.start();
    }

    public void setHandler(final Handler mHandler) {
        this.mHandler = mHandler;
    }

    private boolean IsTargetDevice(UsbDevice usb) {
        if (mVendorID == usb.getVendorId() && mProductID == usb.getProductId())
            return true;
        return false;
    }

    private void OpenUsbDevice(UsbDevice usb) {
        if (usb == null)
            return;

        AtmosLogger.e(TAG, "OpenUsbDevice");

        mUsbDevice = usb;
        int interfaceCount = usb.getInterfaceCount();
        for (int i = 0; i < interfaceCount; i++) {
            mInterface = usb.getInterface(i);
            if (mInterface.getInterfaceClass() == UsbConstants.USB_CLASS_HID) {
                break;
            }
        }
        if (mInterface != null) {
            for (int j = 0; j < mInterface.getEndpointCount(); j++) {
                UsbEndpoint endpoint = mInterface.getEndpoint(j);
                if (endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
                    if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
                        usbEpOut = endpoint;
                    } else {
                        usbEpIn = endpoint;
                    }
                }
            }

            if (!mUsbManager.hasPermission(usb)) {
                TryGetUsbPermission();
            } else {
                GotUsbPermission(usb);
            }

        } else {
            AtmosLogger.e(TAG, "没有找到设备接口！");
        }
    }

    private void ReadFromUsb() {
        if (mDeviceConnection != null && usbEpIn != null) {
            StringBuffer sb = new StringBuffer();
            byte[] receivebytes = new byte[64];  //根据设备实际情况写数据大小
            int ret = mDeviceConnection.bulkTransfer(usbEpIn, receivebytes, receivebytes.length, 100);
            if (ret > 0) {
                for (int i = 0; i < ret; i++) {
                    sb.append(String.format(" %02x", receivebytes[i]));
                    recvBytes.append(String.format(" %02x", receivebytes[i]));
                }
                AtmosLogger.e(TAG, "接收数据(长度" + ret + "):" + sb.toString());

                byteNum += ret;

                //if(ret == 7)
                {
                    if (receivebytes[2] == 0x01) {
                        state = receivebytes[3];
                        coinNum = receivebytes[5];
                        coinNum <<= 8;
                        coinNum += receivebytes[4];
                        keyState = receivebytes[6] & 0x0F;
                        ver = receivebytes[7];
                        SendToUsb(receivebytes, ret);
                    }
                }

                mHandler.sendEmptyMessage(2);

            }
        }
    }

    public int getCoinNum() {
        return coinNum;
    }

    public int getStatus() {
        return state;
    }

    public void SendCmd(int _cmd, int _num) {
        byte[] _bytes = new byte[6];
        _bytes[0] = (byte) 0x88;
        int _len = 0;
        _bytes[2] = (byte) _cmd;
        switch (_cmd) {
            case 1:
                break;
            case 2:
                _len = 4;
                _bytes[3] = (byte) _num;
                _bytes[4] = (byte) (_num >> 8);
                break;
            case 3:
                _len = 3;
                _bytes[3] = (byte) _num;
                break;
        }
        _bytes[1] = (byte) _len;

        for (int i = 1; i < _len + 1; i++) {
            _bytes[_len + 1] ^= _bytes[i];
        }
        SendToUsb(_bytes, _len + 2);
    }

    //USB发送和接收测试
    private void SendToUsb(byte[] _bytes, int _len) {
        if (mDeviceConnection == null)
            return;
        int ret = -1;
        ret = mDeviceConnection.bulkTransfer(usbEpOut, _bytes, _len, 3000);
        AtmosLogger.e(TAG, "指令已经发送！" + ret);
    }

    private void GotUsbPermission(UsbDevice usb) {
        if (mUsbManager.hasPermission(usb)) {
            // 打开设备，获取 UsbDeviceConnection 对象，连接设备，用于后面的通讯
            mDeviceConnection = mUsbManager.openDevice(mUsbDevice);
            if (mDeviceConnection == null) {
                return;
            }

            if (mDeviceConnection.claimInterface(mInterface, true)) {
                AtmosLogger.e(TAG, "找到设备接口");

                mThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                break;
                            }
                            ReadFromUsb();
                        }
                    }
                });
                mThread.start();

            } else {
                mDeviceConnection.close();
            }

        } else {
            AtmosLogger.e(TAG, "没有权限");
        }
    }

    private void TryGetUsbPermission() {
        BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                    context.unregisterReceiver(this);
                    synchronized (this) {
                        UsbDevice usb = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (!IsTargetDevice(usb)) {
                            return;
                        }
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if (usb != null) {
                                AtmosLogger.e(TAG, usb.getDeviceName() + "已获取USB权限");
                                GotUsbPermission(usb);
                            }
                        } else {
                            AtmosLogger.e(TAG, String.valueOf("USB权限已被拒绝，Permission denied for device" + usb));
                        }
                    }

                }
            }
        };

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);

        if (mUsbPermissionActionReceiver != null) {
            mContext.registerReceiver(mUsbPermissionActionReceiver, filter);
        }

        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);

        boolean hasTargetDevice = false;
        for (final UsbDevice usb : mUsbManager.getDeviceList().values()) {
            if (IsTargetDevice(usb)) {
                hasTargetDevice = true;
                AtmosLogger.e(TAG, usb.getDeviceName() + "已找到USB设备");
                if (mUsbManager.hasPermission(usb)) {
                    AtmosLogger.e(TAG, usb.getDeviceName() + "已获取过USB权限");
                } else {
                    AtmosLogger.e(TAG, usb.getDeviceName() + "请求获取USB权限");
                    mUsbManager.requestPermission(usb, mPermissionIntent);
                }
            }

        }

        if (!hasTargetDevice) {
            AtmosLogger.e(TAG, "未找到USB设备");
        }
    }
}
